//
//  HexStringToGeneralString.m
//  TestDemo
//
//  Created by myApple on 16/2/25.
//  Copyright © 2016年 myApple. All rights reserved.
//

#import "HexStringToGeneralString.h"

@interface HexStringToGeneralString()
{
    int allNumber[256];
    int indexZero[34];//通过值来记住那个是零
    char replace;
}

@end

@implementation HexStringToGeneralString

-(id)init
{
    self = [super init];
    if (self) {
        for (int i = 0; i < 256; i++) {
            allNumber[i] = i;
            if (i<34) {
                indexZero[i] = 0;
            }
        }
        
    }
    return self;
}

#pragma mark -------- 十六进制的字符串转化为普通字符串
-(NSString *)stringFromHexString:(NSString *)hexString {
    char *myBuffer = (char *)malloc((int)[hexString length] / 2 + 1);
    int t = 0;
    bzero(myBuffer, [hexString length] / 2 + 1);
    for (int i = 0; i < [hexString length] - 1; i += 2) {
        unsigned int anInt;
        NSString * hexCharStr = [hexString substringWithRange:NSMakeRange(i, 2)];
        //十六进制转化为十进制
        NSScanner * scanner = [[NSScanner alloc] initWithString:hexCharStr];
        [scanner scanHexInt:&anInt];
        //三十四个数字，根据下标来找到零的位置
        if (anInt == 0) {
            indexZero[t] = i/2;
            t++;
        }
        //256个数字，所有出现的值都令其为0
        allNumber[anInt] = 0;
        myBuffer[i / 2] = (char)anInt;
    }
    //从allNumber中找出最近一个不为0的值来替换0的数字
    for (int k = 0; k< 256; k++) {
        if (allNumber[k] != 0) {
            replace = (char)allNumber[k];
            break;
        }
    }
    //通过下标来找为零的位置将其替换掉
    for (int j = 0; j <= t; j++) {
        if (indexZero[j] != 0) {
            myBuffer[indexZero[j]] = replace;
        }
    }
    NSString * replaceChar = [NSString stringWithFormat:@"%c",replace];
    NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingISOLatin1);
    NSString *unicodeString = [NSString stringWithCString:myBuffer encoding:enc];
    //按照编码转换后，还要把零给转换过来
    unicodeString = [unicodeString stringByReplacingOccurrencesOfString:replaceChar withString:@"\0"];
    return unicodeString;
}

-(ZXImage *)prepareCardView:(NSString *)string
{
    if (!string) {
        return nil;
    }
    else
    {
        
        ZXMultiFormatWriter *writer = [[ZXMultiFormatWriter alloc] init];
        ZXBitMatrix *result = [writer encode:string
                                      format:kBarcodeFormatQRCode
                                       width:200
                                      height:200
                                       error:nil];
        
        
        if (result) {
            ZXImage *image = [ZXImage imageWithMatrix:result];
            return image;
        }
        return nil;
    }
}


@end
